﻿using Edge.Repository.Model.CameraSys;
using Edge.Repository.Model.CameraSys.CDal;
using HYRN.Common.ConvertUtilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZedGraph;

namespace CameraClient.CForm.CameraF
{
    public partial class FormChartAll : Form
    {
        public FormChartAll()
        {
            InitializeComponent();
        }

        public int PointCount = 200;

        List<Color> mytColors = new List<Color>();

        private void FormChartAll_Load(object sender, EventArgs e)
        {
            flowLayoutPanel1.Controls.Clear();

            CameraService dal = new CameraService();
            List<CameraConfigModel> cameras = dal.Query();
            foreach (CameraConfigModel cam in cameras)
            {
                CheckBox checkBox = new CheckBox();
                checkBox.Name = "cb_" + cam.Id;
                checkBox.Text = cam.Name;
                checkBox.Tag = cam;
                checkBox.Checked = false;
                flowLayoutPanel2.Controls.Add(checkBox);
            }


            listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown);
            listBox1.MouseUp += new MouseEventHandler(listBox1_MouseUp);
            listBox1.MouseMove += new MouseEventHandler(listBox1_MouseMove);

            listBox1.DataSource = cameras.Select(F => F.Name).ToList();


            dateTimePicker1.Value = DateTime.Now;
            dateTimePicker2.Value = DateTime.Now.AddHours(-1);

            dateTimePicker4.Value = DateTime.Now;
            dateTimePicker3.Value = DateTime.Now;


            mytColors = GetColors();

        }
        #region MyRegion
        private bool isMouseDown = false;
        private List<object> selectedItems = new List<object>();

        void listBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (isMouseDown && e.Button == MouseButtons.Left)
            {
                int index = listBox1.IndexFromPoint(e.X, e.Y);
                if (index != ListBox.NoMatches && !selectedItems.Contains(listBox1.Items[index]))
                {
                    selectedItems.Add(listBox1.Items[index]);
                    listBox1.SelectedIndices.Add(index);
                }
            }
        }

        void listBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = false;
                listBox1.SelectedItems.Clear(); // Clear the selection to prevent duplication
                foreach (var item in selectedItems)
                {
                    listBox1.SelectedItems.Add(item); // Add the selected items to the control
                }
                selectedItems.Clear(); // Clear the temporary selection list
            }
        }

        void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = true;
                selectedItems.Clear(); // Clear the temporary selection list
                listBox1.SelectedIndices.Clear(); // Clear the control's selection
            }
        }


        #endregion
        private void button1_Click(object sender, EventArgs e)
        {
            List<string> selectedItems = new List<string>();

            /// 第一种
            //List<string> selectedItems = listBox1.SelectedItems.Cast<string>().ToList();
            //foreach (string item in selectedItems)
            //{
            //    Console.WriteLine(item);
            //}

            foreach (var item in flowLayoutPanel2.Controls)
            {
                if (item is CheckBox)
                {
                    CheckBox checkBox = (CheckBox)item;
                    if (checkBox.Checked)
                    {
                        selectedItems.Add(checkBox.Text);
                    }
                }
            }

            ShowView(selectedItems);
        }


        public List<CameraConfigModel> GetSelControl()
        {
            List<CameraConfigModel> cameras = new List<CameraConfigModel> { };

            foreach (Control control in flowLayoutPanel1.Controls)
            {
                if (control is CheckBox)
                {
                    CheckBox check = (CheckBox)control;

                    if (check.Checked)
                    {
                        CameraConfigModel item = (CameraConfigModel)check.Tag;
                        if (item != null)
                        {
                            cameras.Add(item);
                        }
                    }
                }
            }
            return cameras;
        }



        public List<CameraConfigModel> GetSelControl(List<string> selectedItems)
        {
            if (selectedItems == null || selectedItems.Count == 0) { return null; }

            CameraService dal = new CameraService();
            List<CameraConfigModel> cameras = dal.Query().Where(F => selectedItems.Contains(F.Name)).ToList();
            return cameras;
        }



        public void ShowView(List<string> selectedItems)
        {
        
            List<CameraConfigModel> cameras = GetSelControl(selectedItems);
            if (cameras == null || cameras.Count == 0)
            {
                MessageBox.Show("未查询到相关数据");
                return;
            }
            List<int> pids = cameras.Select(cam => cam.Id).ToList();


            int maxWenDu = 5000;
            int minWenDu = 0;
            if (cameras != null && cameras.Count > 0)
            {
                maxWenDu = cameras.Max(cam => cam.MaxWenDu);
                minWenDu = cameras.Min(cam => cam.MinWenDu);
            }

            CameraDataService cameraDal = new CameraDataService();

            DateTime dateTimeA = (dateTimePicker1.Value.ToString("yyyy-MM-dd") + " " + dateTimePicker2.Value.ToString("HH:mm:ss")).ObjToDate();
            DateTime dateTimeB = (dateTimePicker4.Value.ToString("yyyy-MM-dd") + " " + dateTimePicker3.Value.ToString("HH:mm:ss")).ObjToDate();

          

            List<DateTime> xTimes = new List<DateTime>();
            string shijian = "";
         

            string xianTitle = "";

            List<CChartShowData> cChartShowDatas = new List<CChartShowData>();

            bool isFirst = true;
            foreach (var cam in cameras)
            {
                // 获取单个源数据

                int listcount = cameraDal.Query(F =>
              (F.Pid == cam.Id) &&
                F.CreateTime >= dateTimeA && F.CreateTime < dateTimeB).Count();


                List<CameraDataModel> listItem = new List<CameraDataModel>();
                if (listcount <= PointCount)
                {
                    listItem = cameraDal.Query(F =>
                     (F.Pid == cam.Id) &&
                       F.CreateTime >= dateTimeA && F.CreateTime < dateTimeB)
                   .OrderBy(F => F.Id).ToList();
                }
                else
                {
                    int jiange = listcount / PointCount;
                    listItem = cameraDal.GetList(dateTimeA, dateTimeB, cam.Id, jiange);
                }



                if (string.IsNullOrEmpty(xianTitle))
                {
                    xianTitle = "'" + cam.Name.ToString() + "'";
                }
                else { xianTitle = shijian + ",'" + cam.Name.ToString() + "'"; }


                List<string> wenduOnes = new List<string>();

                if (isFirst)
                {
                    foreach (CameraDataModel item in listItem)
                    {

                        isFirst = false;
                        xTimes.Add(item.CreateTime);
                        if (string.IsNullOrEmpty(shijian)) { shijian = "'" + item.CreateTime.ToString() + "'"; }
                        else { shijian = shijian + ",'" + item.CreateTime.ToString() + "'"; }


                    }
                }


                foreach (CameraDataModel item in listItem)
                {

                    wenduOnes.Add(item.WenDu.ObjToInt() == 0 ? "'-'" : item.WenDu.ObjToInt().ObjToString());


                    if (maxWenDu < item.WenDu.ObjToInt()) {
                        maxWenDu = item.WenDu.ObjToInt();
                    }

                     

                    if (minWenDu > item.WenDu.ObjToInt())
                    {
                        minWenDu = item.WenDu.ObjToInt();
                    }



                }

                cChartShowDatas.Add(new CChartShowData()
                {
                    Name = cam.Name,
                    WenduOnes = wenduOnes
                });

            }

            CChartShowDto showDto = CChartHelper.GetShowQuXianData(cChartShowDatas);

            showDto.Xzhou = shijian;
            showDto.YMax = maxWenDu.ToString();
            showDto.YMin = minWenDu.ToString();

            ShowHtml(showDto);

        }



        public void ShowViewBak(List<string> selectedItems)
        {
            #region 基础数据

            List<CameraConfigModel> cameras = GetSelControl(selectedItems);
            if (cameras == null || cameras.Count == 0)
            {
                MessageBox.Show("未查询到相关数据");
                return;
            }
            List<int> pids = cameras.Select(cam => cam.Id).ToList();


            int maxWenDu = 5000;
            int minWenDu = 0;
            if (cameras != null && cameras.Count > 0)
            {
                maxWenDu = cameras.Max(cam => cam.MaxWenDu);
                minWenDu = cameras.Min(cam => cam.MinWenDu);
            }

            CameraDataService cameraDal = new CameraDataService();

            DateTime dateTimeA = (dateTimePicker1.Value.ToString("yyyy-MM-dd") + " " + dateTimePicker2.Value.ToString("HH:mm:ss")).ObjToDate();
            DateTime dateTimeB = (dateTimePicker4.Value.ToString("yyyy-MM-dd") + " " + dateTimePicker3.Value.ToString("HH:mm:ss")).ObjToDate();

            List<CameraDataModel> list = cameraDal.Query(F =>
                     pids.Contains(F.Pid) &&
                     F.CreateTime >= dateTimeA && F.CreateTime < dateTimeB)
                 .OrderBy(F => F.Id).ToList();

            #endregion
            if (list == null || list.Count == 0)
            {
                MessageBox.Show("未查询到相关数据");
                return;
            }

            DateTime beginTime = list.Min(F => F.CreateTime);
            DateTime endTime = list.Max(F => F.CreateTime);

            TimeSpan Difference = endTime - beginTime; //计算时间差
            int totalFen = Convert.ToInt32(Difference.TotalMinutes).ObjToInt(); //将时间差转换为分钟 

            int jianGeShiChang = 1;


            int pointCount = totalFen / jianGeShiChang;
            if (pointCount < 1) { pointCount = 1; }

            List<DateTime> xTimes = new List<DateTime>();
            string shijian = "";
            for (int i = pointCount + 1; i >= 0; i--)
            {
                DateTime tiemTime = endTime.AddMinutes(-i * jianGeShiChang);
                xTimes.Add(tiemTime);

                if (string.IsNullOrEmpty(shijian)) { shijian = "'" + tiemTime.ToString() + "'"; } else { shijian = shijian + ",'" + tiemTime.ToString() + "'"; }

            }

            string xianTitle = "";

            List<CChartShowData> cChartShowDatas = new List<CChartShowData>();


            foreach (var cam in cameras)
            {
                if (string.IsNullOrEmpty(xianTitle))
                {
                    xianTitle = "'" + cam.Name.ToString() + "'";
                }
                else { xianTitle = shijian + ",'" + cam.Name.ToString() + "'"; }

                List<CameraDataModel> ones = list.FindAll(F => F.Pid == cam.Id);

                List<string> wenduOnes = new List<string>();
                foreach (DateTime t in xTimes)
                {
                    List<CameraDataModel> onesWhere = ones.FindAll(F => F.CreateTime >= t.AddMinutes(-jianGeShiChang) && F.CreateTime <= t.AddMinutes(jianGeShiChang));
                    double wenduOne = 0;
                    if (onesWhere != null && onesWhere.Count > 0)
                    {
                        wenduOne = onesWhere.Select(F => F.WenDu).Average();
                    }
                    wenduOnes.Add(wenduOne.ObjToInt() == 0 ? "'-'" : wenduOne.ObjToInt().ObjToString());
                }

                cChartShowDatas.Add(new CChartShowData()
                {
                    Name = cam.Name,
                    WenduOnes = wenduOnes
                });

            }

            CChartShowDto showDto = CChartHelper.GetShowQuXianData(cChartShowDatas);

            showDto.Xzhou = shijian;
            showDto.YMax = maxWenDu.ToString();
            showDto.YMin = minWenDu.ToString();

            ShowHtml(showDto);


            #region MyRegion


            //string myPath = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "line-all.html");

            //string myPathNew = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "line-all_" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".html");
            //string content = File.ReadAllText(myPath);

            ////  xAxisList: ['14:00', '15:00', '16:00', '17:00', '18:00'],
            //content = content.Replace("{&Xzhou&}", shijian);
            ////  legend: ['温度', '温度1'],
            //content = content.Replace("{&xianTitle&}", showDto.QuXianTitle);
            //content = content.Replace("{&xianseries&}", showDto.QuXianSeries);

            //content = content.Replace("{&ymax&}", maxWenDu.ToString());
            //content = content.Replace("{&ymin&}", minWenDu.ToString());


            //using (StreamWriter sw = new StreamWriter(myPathNew))
            //{
            //    sw.Write(content);
            //}

            //webView2.Url = myPathNew;
            #endregion


        }





        public void ShowHtml(CChartShowDto showDto)
        {


            #region MyRegion


            string myPath = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "line-all.html");

            string myPathNew = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "html");

            if (!Directory.Exists(myPathNew))
            {
                Directory.CreateDirectory(myPathNew);

            }
            myPathNew = Path.Combine(myPathNew, "line-all_" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".html");


            string content = File.ReadAllText(myPath);

            //  xAxisList: ['14:00', '15:00', '16:00', '17:00', '18:00'],
            content = content.Replace("{&Xzhou&}", showDto.Xzhou);
            //  legend: ['温度', '温度1'],
            content = content.Replace("{&xianTitle&}", showDto.QuXianTitle);
            content = content.Replace("{&xianseries&}", showDto.QuXianSeries);

            content = content.Replace("{&ymax&}", showDto.YMax);
            content = content.Replace("{&ymin&}", showDto.YMin);


            using (StreamWriter sw = new StreamWriter(myPathNew))
            {
                sw.Write(content);
            }

            //
            // webView2.Url = myPathNew;

            // chromiumWebBrowser1.LoadUrl(myPathNew);


            System.Diagnostics.Process.Start("explorer.exe", myPathNew);
            #endregion




        }


        public void ShowGraphPane(int maxWenDu, int minWenDu, List<CameraConfigModel> cameras, List<CameraDataModel> list)
        {


            #region Zbase

            this.z1.GraphPane.Title.Text = ""; //米字测温折线图
            this.z1.GraphPane.XAxis.Title.Text = "时间";
            this.z1.GraphPane.YAxis.Title.Text = "温度";
            this.z1.GraphPane.XAxis.Type = ZedGraph.AxisType.Date;

            this.z1.GraphPane.YAxis.Scale.Max = maxWenDu;
            this.z1.GraphPane.YAxis.Scale.Min = minWenDu;
            // this.z1.GraphPane.YAxis.Scale.MinorStep = 100;


            //this.z1.GraphPane.XAxis.Scale.Min = 120;
            //this.z1.GraphPane.XAxis.Scale.Max = 0;




            z1.GraphPane.CurveList.Clear();

            #endregion


            int colorIndex = 0;
            foreach (var item in cameras)
            {
                #region MyRegion
                List<CameraDataModel> itemList = new List<CameraDataModel>();
                itemList = list.FindAll(F => F.Pid == item.Id);

                PointPairList list_ZhongXin = new PointPairList();

                PointPairList list_ZuiGao = new PointPairList();

                int mycount = 50;
                if (itemList != null && itemList.Count > mycount)
                {

                    int fenshu = itemList.Count / mycount;

                    for (int i = 0; i < mycount; i++)
                    {
                        int index = (i * fenshu);

                        CameraDataModel dto = itemList[index];

                        list_ZhongXin.Add(new PointPair
                        {
                            X = (double)new XDate(dto.CreateTime),
                            Y = Convert.ToDouble(dto.WenDu),
                            Tag = dto.CreateTime
                        });

                    }
                }
                else
                {

                    foreach (CameraDataModel dto in itemList)
                    {
                        #region MyRegion

                        // 圆点温度
                        list_ZhongXin.Add(new PointPair
                        {
                            X = (double)new XDate(dto.CreateTime),
                            Y = Convert.ToDouble(dto.WenDu),
                            Tag = dto.CreateTime
                        });

                        #endregion 
                    }

                }
                // z1.IsShowPointValues = true;


                #region 添加到试图


                { z1.GraphPane.AddCurve(item.Name + "温度", list_ZhongXin, mytColors[colorIndex], SymbolType.None); }
                colorIndex = colorIndex + 1;
                #endregion

                #endregion
            }



            z1.AxisChange();
            z1.Invalidate();


        }


        public List<Color> GetColors()
        {
            List<Color> colors = new List<Color>();

            colors.Add(Color.Black);
            colors.Add(Color.Red);
            colors.Add(Color.Yellow);
            colors.Add(Color.Green);
            colors.Add(Color.Gray);


            for (int i = 0; i < 50; i++)
            {
                colors.Add(RanDomColor());
            }


            return colors;
        }


        private Color RanDomColor()
        {

            //long tick = DateTime.Now.Ticks;
            //Random ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));

            //int R = ran.Next(255);
            //int G = ran.Next(255);
            //int B = ran.Next(255);
            //B = (R + G > 400) ? R + G - 400 : B;//0 : 380 - R - G;
            //B = (B > 255) ? 255 : B;
            //return Color.FromArgb(R, G, B);


            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
            //  对于C#的随机数，没什么好说的
            System.Threading.Thread.Sleep(RandomNum_First.Next(50));
            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
            //  为了在白色背景上显示，尽量生成深色
            int int_Red = RandomNum_First.Next(256);
            int int_Green = RandomNum_Sencond.Next(256);
            int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
            int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            return Color.FromArgb(int_Red, int_Green, int_Blue);


        }



    }
}
